{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Rules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This tutorial is available as an IPython notebook at [Malaya/example/augmentation-rules](https://github.com/huseinzol05/Malaya/tree/master/example/augmentation-rules).\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3.17 s, sys: 3.28 s, total: 6.46 s\n",
      "Wall time: 2.31 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "import malaya"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Why augmentation\n",
    "\n",
    "Let say you have a very limited labelled corpus, and you want to add more, but labelling is very costly.\n",
    "\n",
    "So, text augmentation! We provided few augmentation interfaces in Malaya."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Synonym\n",
    "\n",
    "Use dictionary of synonym to replace words with it synonyms. Synonym data from [Malaya-Dataset/90k-synonym](https://github.com/huseinzol05/Malaya-Dataset#90k-synonym).\n",
    "\n",
    "```python\n",
    "def synonym(\n",
    "    string: str,\n",
    "    threshold: float = 0.5,\n",
    "    top_n = 5,\n",
    "    **kwargs\n",
    "):\n",
    "    \"\"\"\n",
    "    augmenting a string using synonym, https://github.com/huseinzol05/Malaya-Dataset#90k-synonym\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    string: str\n",
    "        this string input assumed been properly tokenized and cleaned.\n",
    "    threshold: float, optional (default=0.5)\n",
    "        random selection for a word.\n",
    "    top_n: int, (default=5)\n",
    "        number of nearest neighbors returned. Length of returned result should as top_n.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "string = 'saya suka makan ayam dan ikan'\n",
    "text = 'Perdana Menteri berkata, beliau perlu memperoleh maklumat terperinci berhubung isu berkenaan sebelum kerajaan dapat mengambil sebarang tindakan lanjut. Bagaimanapun, beliau yakin masalah itu dapat diselesaikan dan pentadbiran kerajaan boleh berfungsi dengan baik.'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = malaya.preprocessing.Tokenizer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['saya mencinta merampas ternakan dan ikan',\n",
       " 'saya mencinta merampas ternakan dan ikan',\n",
       " 'saya sukanya dilucutkan ternakan dan ikan',\n",
       " 'saya berkenan dilucutkan ternakan dan ikan',\n",
       " 'saya berkenan melucutkan ternakan dan ikan']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.augmentation.rules.synonym(' '.join(tokenizer.tokenize(string)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Perdana Menteri teragak-agak , beliau mandatori melahirkan Laporan terperinci berhubung isu berkenaan di hadapan negeri menggunakannya menggendong sebarang hal lanjut . masih , beliau yakin persoalan itu dapatkan diselesaikan dan pentadbiran kekaisaran boleh berbunyi dengan elok .',\n",
       " 'Perdana uskup teragak-agak , beliau mandatori melahirkan Laporan terperinci berhubung isu berkenaan sebelum ranah menggunakannya menjaga sebarang hal lanjut . masih , beliau yakin persoalan itu dapatkan diselesaikan dan pentadbiran kekaisaran mampu berbunyi dengan cantik .',\n",
       " 'Utama gajah meraba , beliau perlu menggambarkan Pengajian terperinci berhubung isu berkenaan pendahuluan dunia memikul melembutkan sebarang tajuk lanjut . bagaimanapun , beliau beranggapan masalah itu meraih diselesaikan dan pentadbiran kekaisaran layak jalan dengan kecantikan .',\n",
       " 'Tinggi menteri meraba , beliau mustahak menggambarkan Laporan terperinci mencakup isu berkenaan penyertaan dunia makan melembut sebarang tajuk lanjut . masih , beliau beranggapan persoalan itu meraih diselesaikan dan arahan negara layak runut dengan lawa .',\n",
       " 'Tinggi menteri meraba , beliau mustahak menggambarkan Berita terperinci mencakup hal berkenaan lontaran dunia menghabiskan melembut sebarang tajuk memajukan . masih , beliau menyangka masalahnya itu meraih diselesaikan dan tauliah negara layak selat dengan lawa .']"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.augmentation.rules.synonym(' '.join(tokenizer.tokenize(text)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Replace consonants\n",
    "\n",
    "```python\n",
    "def replace_similar_consonants(\n",
    "    word: str,\n",
    "    threshold: float = 0.5,\n",
    "    replace_consonants: Dict[str, List[str]] = {\n",
    "        'n': ['m'],\n",
    "        'r': ['t', 'q'],\n",
    "        'g': ['h'],\n",
    "        'j': ['k'],\n",
    "        'k': ['l'],\n",
    "        'd': ['s', 'f'],\n",
    "        'g': ['f', 'h'],\n",
    "        'b': ['n'],\n",
    "        'f': ['p'],\n",
    "    }\n",
    "):\n",
    "    \"\"\"\n",
    "    Naively replace consonants with another consonants to simulate typo or slang\n",
    "    if after consonants is a vowel.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    word: str\n",
    "    threshold: float, optional (default=0.5)\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 memunjukkan\n",
      "1 memunjukkan\n",
      "2 menunkuklam\n",
      "3 memunkukkan\n",
      "4 memunkukkam\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.replace_similar_consonants('menunjukkan'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Replace vowels\n",
    "\n",
    "```python\n",
    "def replace_similar_vowels(\n",
    "    word: str,\n",
    "    threshold: float = 0.5,\n",
    "    replace_vowels: Dict[str, List[str]] = {\n",
    "        'u': ['o'],\n",
    "        'a': ['o'],\n",
    "        'i': ['o'],\n",
    "        'o': ['u'],\n",
    "    }\n",
    "):\n",
    "    \"\"\"\n",
    "    Naively replace vowels with another vowels to simulate typo or slang\n",
    "    if after vowels is a consonant.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    word: str\n",
    "    threshold: float, optional (default=0.5)\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: str\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 menunjokkan\n",
      "1 menonjukkan\n",
      "2 menunjukkan\n",
      "3 menunjukkon\n",
      "4 menonjokkon\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.replace_similar_vowels('menunjukkan'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Social media word structure\n",
    "\n",
    "```python\n",
    "def socialmedia_form(word: str):\n",
    "    \"\"\"\n",
    "    augmenting a word into socialmedia form.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    word: str\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 []\n",
      "1 []\n",
      "2 []\n",
      "3 []\n",
      "4 []\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.socialmedia_form('menunjukkan'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 kotok\n",
      "1 katok\n",
      "2 katok\n",
      "3 katak\n",
      "4 katok\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.replace_similar_vowels('katak'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 sedora\n",
      "1 sedara\n",
      "2 sedora\n",
      "3 sedara\n",
      "4 sedoro\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.replace_similar_vowels('sedara'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### remove vowel in alternative ways"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 menunjkkan\n",
      "1 menunjkkn\n",
      "2 mnnjukkn\n",
      "3 mnnjukkn\n",
      "4 mennjkkn\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i, malaya.augmentation.rules.vowel_alternate('menunjukkan'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Kelantanese word structure\n",
    "\n",
    "```python\n",
    "def kelantanese_form(word: str):\n",
    "    \"\"\"\n",
    "    augmenting a word into kelantanese form.\n",
    "    `ayam` -> `ayom`\n",
    "    `otak` -> `otok`\n",
    "    `kakak` -> `kakok`\n",
    "\n",
    "    `barang` -> `bare`\n",
    "    `kembang` -> `kembe`\n",
    "    `nyarang` -> `nyare`\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    word: str\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['bare']"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.augmentation.rules.kelantanese_form('barang')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['otok']"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.augmentation.rules.kelantanese_form('otak')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['kembe']"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.augmentation.rules.kelantanese_form('kembang')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
